<template>
  <div id="app" style="overflow: hidden;width:100%;height:100%;">
    <vxe-grid ref="xGrid" v-bind="grid_options" :row-config="{height:36}" @form-reset="formResetEvent">
    </vxe-grid>
    <!--  @click="viewPhoto(udsUrl+row.sbzp+'/user.jpg')"  -->
    <baseInfo ref="baseInfo"></baseInfo>
    <workOrderModel ref="workOrderModel"></workOrderModel>
    <workOrderModel2 ref="workOrderModel2"></workOrderModel2>
    <workOrderModel3 ref="workOrderModel3"></workOrderModel3>
  </div>


</template>

<script>
import {reactive} from 'vue'
import {defectLibraryApi} from "@/api/defects/defectLibraryApi.js"
import {GridEvent} from "./model/defectLibraryTable.js"
import baseInfo from "./components/baseInfo.vue"
import workOrderModel from "./components/workOrderModel1.vue"
import workOrderModel2 from "./components/workOrderModel2.vue"
import workOrderModel3 from "./components/workOrderModel3.vue"
import util from '@/utils/util'
import VXETable from "vxe-table";

export default {
  name: 'defectLibrary',
  components: {baseInfo, workOrderModel, workOrderModel2, workOrderModel3},
  props: {
    row: {
      type: Object,
    },
    formData: {
      type: Object,
    },
  },
  data() {
    return {
      time: '',
      etime: '',
      equipDefectType: '',
      defectStatusCode: '',
      GridEvent: reactive(GridEvent),
      grid_options: {
        border: true,
        stripe: true,
        showHeaderOverflow: true,
        showOverflow: true,
        keepSource: true,
        id: 'full_edit_1',
        height: 700,
        rowId: 'id',  //指定记录主键
        rowConfig: {
          isHover: true
        },
        columnConfig: {
          resizable: true
        },
        customConfig: {
          storage: true,
          // checkMethod: this.checkColumnMethod
        },
        sortConfig: {
          trigger: 'cell',
          remote: true
        },
        filterConfig: {
          remote: true
        },
        formConfig: {
          form: true, // 启用表单代理
          size: "medium",        //尺寸
          titleAlign: "right",  //所有项的标题对齐方式
          titleWidth: "120", //标题宽度
          titleColon: true,     //是否显示标题冒号
          collapseStatus: false,//折叠
          items: [
            {
              field: 'unitNo',
              title: '单位:',
              span: 6,
              itemRender: {name: '$select', options: [], props: {placeholder: '---请选择---'}}
            },
            {
              field: 'defectName',
              title: '缺陷隐患名称:',
              span: 6,
              itemRender: {name: '$input', props: {placeholder: '请输入'}}
            },
            {
              field: 'equipName',
              title: '设备名称:',
              span: 6,
              itemRender: {name: '$input', props: {placeholder: '请输入'}}
            },
            {
              field: 'equipDefectType',
              title: '问题分类:',
              span: 6,
              itemRender: {name: '$select', options: [], props: {placeholder: '---请选择---'}},
              folding: true
            },
            {
              field: 'taskSourceNo',
              title: '数据来源',
              span: 6,
              itemRender: {name: '$select', options: [], props: {placeholder: '---请选择---'}},
              folding: true
            },
            {
              field: 'creatTime',
              title: '发现日期',
              span: 6,
              folding: true,
              itemRender: {name: '$input', props: {type: 'datetime', placeholder: '---请输入---'}}
            },
            {
              field: 'creatTime_to',
              title: '至',
              span: 6,
              folding: true,
              itemRender: {name: '$input', props: {type: 'datetime', placeholder: '---请输入---'}}
            },
            {
              field: 'defectStatusCode',
              title: '处理状态:',
              span: 6,
              folding: true,
              itemRender: {name: '$select', options: [], props: {placeholder: '---请选择---'}},
            },
            {
              span: 6, collapseNode: true, align: 'right', itemRender: {
                name: '$buttons', children: [
                  {props: {type: 'submit', content: '查询', status: 'primary', icon: 'fa fa-search'}},
                  {props: {type: 'reset', content: '重置', icon: 'fa fa-reply'}},
                ]
              }
            }
          ]
        },
        toolbarConfig: {
          buttons: [
            {buttonRender: {name: 'add', events: {click: this.addRowModal}}}, // 新增

          ],
          refresh: true,
          custom: true,
        },
        pagerConfig: {
          pageSize: 10,
          pageSizes: [5, 10, 15, 20, 50, 100],
          layouts: ['PrevJump', 'PrevPage', 'JumpNumber', 'NextPage', 'NextJump', 'Sizes', 'FullJump', 'Total'],
          background: true,
        },
        proxyConfig: {
          seq: true, // 启用动态序号代理，每一页的序号会根据当前页数变化
          sort: true, // 启用排序代理，当点击排序时会自动触发 query 行为
          filter: true, // 启用筛选代理，当点击筛选时会自动触发 query 行为
          form: true, // 启用表单代理，当点击表单提交按钮时会自动触发 reload 行为
          // 对应响应结果 { result: [], page: { total: 100 } }
          props: {
            result: 'data.records', // 配置响应结果列表字段
            total: 'data.total' // 配置响应结果总页数字段
          },
          // 只接收Promise，具体实现自由发挥
          ajax: {
            // 当点击工具栏查询按钮或者手动提交指令 query或reload 时会被触发
            query: async ({page, sorts, filters, form}) => {
              // =====给表单项赋初始值======
              await this.initFormData(form);
              //    this.enableDefault = false;
              const queryParams = Object.assign({}, form)
              // const queryParams = this.initFormData(form)
              // 处理排序条件
              const firstSort = sorts[0]
              if (firstSort) {
                queryParams.sort = firstSort.property
                queryParams.order = firstSort.order
              }
              // 处理筛选条件

              filters.forEach(({property, values}) => {
                queryParams[property] = values.join(',')
              })
              return this.queryData(page, queryParams)
            },
          }
        },
        columns: [
          {type: 'seq', title: '序号', width: "60px", align: 'center', headerAlign: 'center'},
          {field: 'unitName', title: '单位名称', minWidth: "160px", align: 'center', headerAlign: 'center',},
          {field: 'defectStatusName', title: '处理状态', minWidth: "160px", align: 'center', headerAlign: 'center',},
          {
            field: 'defectName',
            title: '缺陷隐患名称',
            minWidth: "160px",
            align: 'center',
            headerAlign: 'center',
            cellRender: {name: 'defectName', events: {click: this.handleBaseInfo}}
          },
          {
            field: 'handleTaskName',
            title: '消缺工单名称',
            minWidth: "160px",
            align: 'center',
            headerAlign: 'center',
            cellRender: {name: 'handleTaskName', events: {click: this.workOrderModel}}
          },
          {field: 'taskSourceName', title: '数据来源', minWidth: "160px", align: 'center', headerAlign: 'center',},
          {field: 'equipDefectTypeName', title: '问题分类', minWidth: "160px", align: 'center', headerAlign: 'center',},
          {field: 'creator', title: '发现人', minWidth: "160px", align: 'center', headerAlign: 'center',},
          {field: 'creatTime', title: '发现日期', minWidth: "160px", align: 'center', headerAlign: 'center',},
          {field: 'defectParts', title: '缺陷隐患部位', minWidth: "160px", align: 'center', headerAlign: 'center',},
          {field: 'defectAddress', title: '缺陷隐患地点', minWidth: "160px", align: 'center', headerAlign: 'center',},
          {field: 'defectDescription', title: '详细描述', minWidth: "160px", align: 'center', headerAlign: 'center'},
          {field: 'equipName', title: '设备名称', minWidth: "160px", align: 'center', headerAlign: 'center',},
          {field: 'equipTypeName', title: '设备类型', minWidth: "160px", align: 'center', headerAlign: 'center',},
          {
            field: 'taskName',
            title: '任务名称',
            minWidth: "160px",
            align: 'center',
            headerAlign: 'center',
            cellRender: {name: 'taskName', events: {click: this.handleWorkModel}}
          },
          {
            field: 'beforePictureIds',
            title: '消缺前照片',
            minWidth: "160px",
            align: 'center',
            headerAlign: 'center',
            cellRender: {name: 'beforePictureIds'}
          },
          {
            field: 'afterPictureIds',
            title: '消缺后照片',
            minWidth: "160px",
            align: 'center',
            headerAlign: 'center',
            cellRender: {name: 'afterPictureIds'}
          },
          {field: 'qxyhXqsj', title: '处理日期', minWidth: "160px", align: 'center', headerAlign: 'center',},
        ],
        checkboxConfig: {
          // labelField: 'id',
          reserve: true,
          highlight: true,
          range: true
        },
        editConfig: {
          trigger: 'click',
          mode: 'row',
          showStatus: true
        }
      },
      //  api: 'fetchQueryQueryRwxqByPage',
      // init: true
      kfOptions: [],
      enableDefault: true
    }
  },
  created() {

  },
  mounted() {
    this.$nextTick(function () {
      GridEvent.getOptionData_gldw(this.$refs.xGrid)//单位名称
      GridEvent.getOptionData_sjly(this.$refs.xGrid)//数据来源
      GridEvent.getOptionData_clzt(this.$refs.xGrid)//处理状态
      GridEvent.getOptionData_wtfl(this.$refs.xGrid)//问题类型
      this.setReadModel()
    })
    window.addEventListener('resize', this.setTableHeight);
  },
  destroyed: function () {
    window.removeEventListener('resize', this.setTableHeight);
  },
  methods: {
    timeformat(dat, value, type) {
      let year = dat.getFullYear();
      let mon = (dat.getMonth() + 1) < 10 ? "0" + (dat.getMonth() + 1) : dat.getMonth() + 1;
      let data = dat.getDate() < 10 ? "0" + (dat.getDate() - value) : dat.getDate() + value;
      if (type === 'start') {
        var newDate = year + "-" + mon + "-" + data + " " + '00' + ":" + '00' + ":" + '00';
      } else {
        var newDate = year + "-" + mon + "-" + data + " " + '23' + ":" + '59' + ":" + '59';
      }
      return newDate;
    },
    formResetEvent({data}) { // 重置表单
      let datatime = new Date()
      if (this.time) {
        data['creatTime'] = this.time
        data['creatTime_to'] = this.etime
        data['equipDefectType'] = this.equipDefectType
        if (this.defectStatusCode) {
          data['defectStatusCode'] = this.defectStatusCode
        }
      } else {
        data['creatTime'] = this.timeformat(datatime, 0, 'start')
        data['creatTime_to'] = this.timeformat(datatime, 0, 'end')
      }

    },
    // 高度自适应
    setTableHeight: function () {
      const tableContainer = document.querySelector("#app");
      const height = tableContainer.clientHeight;
      this.grid_options.height = height - 5;
    },
    //查询控制
    setReadModel() { //控制是否显示
      const isRead = util.isReadModel()
      if (isRead) {
        this.grid_options.toolbarConfig.buttons = []
      }
      let edate = util.getRequestParms('edate')
      let date = util.getRequestParms('date')
      let equipDefectType = util.getRequestParms('infolx')
      let defectStatusCode = util.getRequestParms('infozt')

      this.equipDefectType = equipDefectType
      this.defectStatusCode = defectStatusCode
      if (date && edate) {
        date = date + ' 00:00:00'
        edate = edate + ' 23:59:59'
        this.time = date
        this.etime = edate
        this.$refs.xGrid._data.formData.creatTime = date
        this.$refs.xGrid._data.formData.creatTime_to = edate
        this.$refs.xGrid._data.formData.equipDefectType = equipDefectType

      }
      if (defectStatusCode) {
        this.$refs.xGrid._data.formData.defectStatusCode = defectStatusCode
      }
    },
    initFormData: async function (form) {
      const that = this;
      let datatime = new Date()
      if (that.enableDefault) {
        // 查询框默认值初识化
        if (this.row !== undefined) {
          form.creatTime = this.formData.creatTime
          form.creatTime_to = this.formData.endTime
        } else {
          form.creatTime = this.timeformat(datatime, 0, 'start')
          form.creatTime_to = this.timeformat(datatime, 0, 'end')
        }
        this.enableDefault = false;
      }
    },
    queryData: (page, formData) => {
      const queryParams = {
        pageSize: page.pageSize,
        pageNo: page.currentPage,
        entity: {
          unitNo: formData.unitNo,
          defectName: formData.defectName,
          jfNo: formData.jfNo,
          equipName: formData.equipName,
          creator: formData.creator,
          creatTime_to: formData.creatTime_to,
          taskSourceNo: formData.taskSourceNo,
          dangerTypeNo: formData.dangerTypeNo,
          creatTime: formData.creatTime,
          defectStatusCode: formData.defectStatusCode,
          materialTypeNo: formData.materialTypeNo,
          equipDefectType: formData.equipDefectType,
        },
        paramsMap: {},
        column: '',
        order: ''
      }
      return defectLibraryApi.page(queryParams)
    },
    handleBaseInfo(row) {
      this.$refs.baseInfo.showDialog(false, row)
    },
    workOrderModel(row) {
      this.$refs.workOrderModel.showDialog(row, false)
    },
    handleWorkModel(row) {

      if (row.taskSourceNo === '1') {
        this.$refs.workOrderModel2.showDialog(row, false)
      } else {
        console.log("00")
        this.$refs.workOrderModel3.showDialog(row, false)
      }
    }

  }
}
//入库编号穿透渲染
VXETable.renderer.add('rkdh', {
  renderDefault(h, renderOpts, params) {
    const {events = {}} = renderOpts
    const {row, column} = params
    return [
      <span onClick={
        () => {
          events.click(params.row)
        }
      }>{params.row.djbm}</span>
    ]
  }
})
VXETable.renderer.add('defectName', {
  // 默认显示模板
  renderDefault(h, renderOpts, params) {
    let {row, column} = params
    let {events} = renderOpts
    return [
      <a style="color:#0000FF;cursor: pointer;" onClick={() => events.click(params)}>{row.defectName}</a>
    ]
  },
})
VXETable.renderer.add('handleTaskName', {
  // 默认显示模板
  renderDefault(h, renderOpts, params) {
    let {row, column} = params
    let {events} = renderOpts
    return [
      <a style="color:#0000FF;cursor: pointer;" onClick={() => events.click(params)}>{row.handleTaskName}</a>
    ]
  },
})
VXETable.renderer.add('taskName', {
  // 默认显示模板
  renderDefault(h, renderOpts, params) {
    let {row, column} = params
    let {events} = renderOpts
    return [
      <a style="color:#0000FF;cursor: pointer;" onClick={() => events.click(row)}>{row.taskName}</a>
    ]
  },
})
VXETable.renderer.add('beforePictureIds', {
  // 默认显示模板
  renderDefault(h, renderOpts, params) {
    let {row, column} = params
    let {events} = renderOpts
    if (row.beforePictureIds && row.beforePictureIds.length > 10) {
      row.beforePictureList = []
      if (row.beforePictureIds.indexOf(',') !== -1) {
        var arr = row.beforePictureIds.split(',')
        if (arr[0].startsWith("https")) {
          row.beforePictureUrl = arr[0];
        }
        arr.map(item => {
          if (item.startsWith("https")) {
            item = item;
          }
          row.beforePictureList.push(item)
        })
      } else {
        if (row.beforePictureIds.startsWith("https")) {
          row.beforePictureUrl = row.beforePictureIds;
        }
        row.beforePictureList.push(row.beforePictureUrl)
      }
    }
    return [
      <el-image v-if={row.beforePictureIds} style="width: 60px; height: 30px;" src={row.beforePictureUrl}
                preview-src-list={row.beforePictureList} alt="">
        <div slot="error" class="imageError">
          <span></span>
        </div>
      </el-image>
    ]
  },
})
VXETable.renderer.add('afterPictureIds', {
  // 默认显示模板
  renderDefault(h, renderOpts, params) {
    let {row, column} = params
    let {events} = renderOpts
    if (row.afterPictureIds && row.afterPictureIds.length > 10) {
      row.afterPictureList = []
      if (row.afterPictureIds.indexOf(',') !== -1) {
        var arr = row.afterPictureIds.split(',')
        if (arr[0].startsWith("https")) {
          row.afterPictureUrl = arr[0];
        }
        arr.map(item => {
          if (item.startsWith("https")) {
            item = item;
          }
          row.afterPictureList.push(item)
        })
      } else {
        if (row.afterPictureIds.startsWith("https")) {
          row.afterPictureUrl = row.afterPictureIds;
        }
        row.afterPictureList.push(row.afterPictureUrl)
      }
    }
    return [
      <el-image v-if={row.afterPictureIds} style="width: 60px; height: 30px;" src={row.afterPictureUrl}
                preview-src-list={row.afterPictureList} alt="">
        <div slot="error" class="imageError">
          <span></span>
        </div>
      </el-image>
    ]
  },
})
</script>

<style scoped>

</style>
